package com.jf.net.converter;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * GsonResponseBodyConverter
 * @author JackyFlame
 * @time 2023/10/23 13:26
 * @description
 */
public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    public GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Nullable
    @Override
    public T convert(ResponseBody value) {
        JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try (value) {
            T result = adapter.read(jsonReader);
            String jsonStr = gson.toJson(result);
            //自动为GPS数据日志增加TAG
            Log.d("JF_NET", "Parse Response Json: " + jsonStr);
            return result;
        } catch (Exception e) {
            Log.e("JF_NET", "Parse Json Error: " + e.getMessage());
            return null;
        }
    }
}
